<template>
  <div class="page-content">
    <!-- 顶部导航 -->
    <header class="bg-white shadow-sm sticky top-0 z-10">
      <div class="container mx-auto px-4 py-3 flex items-center">
        <router-link to="/" class="mr-2">
          <i class="fas fa-arrow-left text-gray-600"></i>
        </router-link>
        <h1 class="text-lg font-semibold">答辩状转换</h1>
      </div>
      <div class="container mx-auto px-4 flex border-b">
        <button
          @click="currentStep = 'case'"
          class="py-3 px-4 font-medium"
          :class="currentStep === 'case' ? 'tab-active' : 'text-gray-500'"
        >
          选择案由
        </button>
        <button
          @click="currentStep = 'upload'"
          class="py-3 px-4 font-medium"
          :class="currentStep === 'upload' ? 'tab-active' : 'text-gray-500'"
        >
          上传答辩状
        </button>
        <button
          @click="currentStep = 'save'"
          class="py-3 px-4 font-medium"
          :class="
            currentStep === 'save' ? 'tab-active' : 'text-gray-500 opacity-50'
          "
        >
          保存分享
        </button>
      </div>
    </header>

    <!-- 选择案由步骤 -->
    <main v-if="currentStep === 'case'" class="container mx-auto px-4 mt-4">
      <div class="bg-white rounded-xl shadow-md p-4">
        <h3 class="font-medium mb-2">全部案由</h3>
        <div class="relative input-highlight mb-4">
          <i class="fas fa-search absolute left-3 top-3 text-gray-400"></i>
          <input
            v-model="searchKeyword"
            type="text"
            placeholder="搜索案由..."
            class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none"
          />
        </div>

        <!-- 搜索结果（有关键词时显示） -->
        <div v-if="searchKeyword" class="max-h-60 overflow-y-auto space-y-2">
          <div
            v-for="item in filteredSearchCases"
            :key="item.category + '-' + item.name"
            @click="selectCase(item.name)"
            class="p-2 rounded hover:bg-gray-100 cursor-pointer flex items-center justify-between"
          >
            <span>
              {{ item.name }}
              <span class="ml-2 text-xs text-gray-400">（{{ item.category }}）</span>
            </span>
            <i v-if="item.hot" class="fas fa-fire text-orange-500 text-xs"></i>
          </div>
        </div>

        <!-- 二级树（无关键词时显示） -->
        <div v-else class="max-h-80 overflow-y-auto divide-y">
          <div v-for="cat in categoryList" :key="cat" class="py-2">
            <!-- 类别头 -->
            <div
              class="flex items-center justify-between px-2 py-1 rounded cursor-pointer hover:bg-gray-50"
              @click="expandedCategories[cat] = !expandedCategories[cat]"
            >
              <div class="font-medium text-gray-800">{{ cat }}</div>
              <i :class="['fas', expandedCategories[cat] ? 'fa-chevron-up' : 'fa-chevron-down', 'text-gray-400']"></i>
            </div>

            <!-- 子项列表 -->
            <div v-show="expandedCategories[cat]" class="mt-1 space-y-1">
              <div
                v-for="(name, idx) in caseMap[cat]"
                :key="cat + '-' + name"
                @click="selectCase(name)"
                class="mx-2 px-2 py-1 rounded hover:bg-gray-100 cursor-pointer flex items-center justify-between"
              >
                <span>{{ name }}</span>
                <i v-if="idx < 11" class="fas fa-fire text-orange-500 text-xs"></i>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 上传答辩状步骤 -->
    <main v-if="currentStep === 'upload'" class="container mx-auto px-4 mt-4">
      <div class="bg-white rounded-xl shadow-md p-6 relative">
        <div class="absolute top-2 right-4 bg-red-100 text-red-600 px-3 py-1 rounded-full text-sm font-medium">
          离婚纠纷
        </div>
        <h2 class="text-lg font-semibold mb-2">上传传统答辩状</h2>
        <p class="text-sm text-gray-500 mb-4">
          支持 JPG/PNG/DOC/DOCX/PDF 格式，文件大小 ≤10MB
        </p>

        <!-- 上传按钮 -->
        <div class="mb-6">
          <button
            @click="showUploadOptions = true"
            class="w-full bg-blue-600 hover:bg-blue-700 text-white py-3 px-4 rounded-lg font-medium flex items-center justify-center"
          >
            <i class="fas fa-plus mr-2"></i>
            <span>选择文件</span>
          </button>
        </div>

        <!-- 上传列表 -->
        <div v-if="uploadList.length > 0" class="mb-6">
          <h3 class="text-sm font-medium text-gray-700 mb-3">上传列表</h3>
          <div class="space-y-3">
            <div
              v-for="(file, index) in uploadList"
              :key="index"
              class="flex items-center p-3 bg-gray-50 rounded-lg"
            >
              <!-- 文件图标 -->
              <div class="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center mr-3">
                <i :class="getFileIcon(file.type)" class="text-blue-600"></i>
              </div>
              
              <!-- 文件信息 -->
              <div class="flex-1 min-w-0">
                <p class="text-sm font-medium text-gray-900 truncate">{{ file.name }}</p>
                <p class="text-xs text-gray-500">{{ formatFileSize(file.size) }}</p>
              </div>
              
              <!-- 上传状态 -->
              <div class="ml-3">
                <!-- 上传中 -->
                <div v-if="file.status === 'uploading'" class="flex items-center">
                  <div class="w-4 h-4 border-2 border-blue-600 border-t-transparent rounded-full animate-spin mr-2"></div>
                  <span class="text-xs text-blue-600">{{ file.progress }}%</span>
                </div>
                
                <!-- 上传成功 -->
                <div v-else-if="file.status === 'success'" class="flex items-center">
                  <i class="fas fa-check-circle text-green-500 mr-1"></i>
                  <span class="text-xs text-green-600">成功</span>
                </div>
                
                <!-- 上传失败 -->
                <div v-else-if="file.status === 'error'" class="flex items-center">
                  <i class="fas fa-times-circle text-red-500 mr-1"></i>
                  <span class="text-xs text-red-600">失败</span>
                </div>
              </div>
              
              <!-- 删除按钮 -->
              <button
                @click="removeFile(index)"
                class="ml-2 p-1 text-gray-400 hover:text-red-500"
              >
                <i class="fas fa-times"></i>
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 上传选项弹窗 -->
      <div
        v-if="showUploadOptions"
        class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-end"
        @click="showUploadOptions = false"
      >
        <div
          class="w-full bg-white rounded-t-xl p-4"
          @click.stop
        >
          <div class="flex items-center justify-between mb-4">
            <h3 class="text-lg font-medium">选择上传方式</h3>
            <button
              @click="showUploadOptions = false"
              class="p-2 text-gray-400 hover:text-gray-600"
            >
              <i class="fas fa-times"></i>
            </button>
          </div>
          
          <div class="grid grid-cols-2 gap-4">
            <!-- 拍照 -->
            <button
              @click="handleUploadOption('camera')"
              class="flex flex-col items-center p-4 bg-gray-50 rounded-lg hover:bg-gray-100"
            >
              <i class="fas fa-camera text-2xl text-blue-600 mb-2"></i>
              <span class="text-sm font-medium">拍照</span>
            </button>
            
            <!-- 相册 -->
            <button
              @click="handleUploadOption('album')"
              class="flex flex-col items-center p-4 bg-gray-50 rounded-lg hover:bg-gray-100"
            >
              <i class="fas fa-images text-2xl text-blue-600 mb-2"></i>
              <span class="text-sm font-medium">相册</span>
            </button>
            
            <!-- 微信文件 -->
            <button
              @click="handleUploadOption('wechat_file')"
              class="flex flex-col items-center p-4 bg-gray-50 rounded-lg hover:bg-gray-100"
            >
              <i class="fab fa-weixin text-2xl text-green-600 mb-2"></i>
              <span class="text-sm font-medium">微信文件</span>
            </button>
            
            <!-- 微信图片 -->
            <button
              @click="handleUploadOption('wechat_image')"
              class="flex flex-col items-center p-4 bg-gray-50 rounded-lg hover:bg-gray-100"
            >
              <i class="fas fa-image text-2xl text-green-600 mb-2"></i>
              <span class="text-sm font-medium">微信图片</span>
            </button>
          </div>
          
          <button
            @click="showUploadOptions = false"
            class="w-full mt-4 py-3 bg-gray-100 text-gray-600 rounded-lg font-medium"
          >
            取消
          </button>
        </div>
      </div>

      <button
        @click="currentStep = 'save'"
        class="w-full mt-6 bg-gradient-to-r from-blue-600 to-blue-500 hover:from-blue-700 hover:to-blue-600 text-white py-3 px-4 rounded-lg font-medium flex items-center justify-center"
        :disabled="uploadList.length === 0"
      >
        <i class="fas fa-magic mr-2"></i>
        <span>AI识别生成</span>
      </button>
    </main>

    <!-- 保存分享步骤 -->
    <main v-if="currentStep === 'save'" class="container mx-auto px-4 mt-4">
      <div class="bg-white rounded-xl shadow-md p-6 mb-6">
        <div class="flex items-center mb-4">
          <div
            class="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center mr-3"
          >
            <i class="fas fa-file-word text-blue-600 text-xl"></i>
          </div>
          <div>
            <h3 class="font-medium">借贷纠纷答辩状.docx</h3>
            <p class="text-sm text-gray-500">2023-06-15 14:30</p>
          </div>
        </div>

        <div class="flex justify-between">
          <div class="text-sm">
            <p class="text-gray-500">文件大小</p>
            <p class="font-medium">356 KB</p>
          </div>
          <div class="text-sm">
            <p class="text-gray-500">转换时间</p>
            <p class="font-medium">2.3 秒</p>
          </div>
        </div>
      </div>

      <div class="grid grid-cols-2 gap-4">
        <button
          @click="downloadFile"
          class="bg-blue-600 hover:bg-blue-700 text-white py-3 px-4 rounded-lg font-medium flex items-center justify-center"
        >
          <i class="fas fa-eye mr-2"></i>
          <span>查看</span>
        </button>
        <button
          @click="shareFile"
          class="bg-green-600 hover:bg-green-700 text-white py-3 px-4 rounded-lg font-medium flex items-center justify-center"
        >
          <i class="fas fa-share-alt mr-2"></i>
          <span>分享</span>
        </button>
      </div>

      <!-- 补充说明与历史入口 -->
      <div class="mt-5 bg-gray-50 rounded-lg p-3">
        <div class="flex items-start text-gray-600 text-sm">
          <i class="fas fa-info-circle mt-0.5 mr-2"></i>
          <p>文档已自动保存，您可以随时在历史文件中查看与再次分享。</p>
        </div>
        <div class="mt-3 flex justify-center">
          <router-link
            to="/usage-history"
            class="inline-flex items-center text-blue-600 hover:text-blue-700 text-sm font-medium"
          >
            <i class="fas fa-history mr-2"></i>
            <span>查看历史文件</span>
          </router-link>
        </div>
      </div>
    </main>
  </div>
</template>

<script>
import { ref, reactive, computed } from "vue";

export default {
  name: "DefenseConvert",
  setup() {
    const currentStep = ref("case");
    const searchKeyword = ref("");
    const uploadProgress = ref(0);
    const isDragOver = ref(false);
    const ocrResult = ref("");
    const fileInput = ref(null);
    const showUploadOptions = ref(false);
    const uploadList = ref([]);

    // 一级分类与二级案由
    const primaryCategories = reactive(["民商事", "执行", "普通行政", "刑事行政"]);
    const selectedPrimary = ref(primaryCategories[0]);
    const expandedCategories = reactive({
      民商事: true,
      执行: false,
      普通行政: false,
      刑事行政: false,
    });

    const caseMap = reactive({
      民商事: [
        "买卖合同纠纷",
        "租赁合同纠纷",
        "物业服务合同纠纷",
        "继承纠纷",
        "侵权责任纠纷",
        "婚姻家庭纠纷",
        "劳动争议纠纷",
        "建设工程纠纷",
        "知识产权纠纷",
        "公司纠纷",
        "证券纠纷",
        "期货纠纷",
        "保险纠纷",
        "票据纠纷",
        "信用证纠纷",
        "融资租赁纠纷",
        "保理纠纷",
        "典当纠纷",
        "民间借贷纠纷",
        "金融借款纠纷",
        "担保纠纷",
        "保证合同纠纷",
        "抵押合同纠纷",
        "质押合同纠纷",
        "定金合同纠纷",
        "居间合同纠纷",
        "委托合同纠纷",
        "行纪合同纠纷",
        "运输合同纠纷",
        "仓储合同纠纷",
        "技术合同纠纷",
        "特许经营合同纠纷",
        "合伙协议纠纷",
        "股权转让纠纷",
        "公司决议纠纷",
      ],
      执行: [
        "执行申请",
        "执行异议",
        "案外人执行异议",
        "执行异议之诉",
        "不予执行仲裁裁决申请",
        "恢复执行申请",
        "执行复议",
        "保全与执行措施异议",
        "中止执行申请",
        "终结执行申请",
        "变更追加当事人申请",
      ],
      普通行政: [
        "行政处罚",
        "行政强制",
        "行政许可",
        "政府信息公开",
        "行政确认",
        "履行法定职责",
        "行政赔偿",
        "行政复议",
        "征收征用",
        "行政不作为",
      ],
      刑事行政: [
        "取保候审申请",
        "变更强制措施申请",
        "解除强制措施申请",
        "国家赔偿申请",
        "会见申请",
        "阅卷申请",
        "申请调取证据",
        "申请重新鉴定",
        "申请回避",
      ],
    });

    const secondaryCases = computed(() => caseMap[selectedPrimary.value] || []);
    const filteredSecondaryCases = computed(() => {
      if (!searchKeyword.value) return secondaryCases.value;
      return secondaryCases.value.filter((caseType) =>
        caseType.toLowerCase().includes(searchKeyword.value.toLowerCase())
      );
    });

    // 扁平搜索结果（显示类别）
    const categoryList = computed(() => Object.keys(caseMap));
    const flattenedCases = computed(() => {
      return categoryList.value.flatMap((cat) =>
        (caseMap[cat] || []).map((name, idx) => ({ category: cat, name, hot: idx < 11 }))
      );
    });
    const filteredSearchCases = computed(() => {
      if (!searchKeyword.value) return [];
      const kw = searchKeyword.value.toLowerCase();
      return flattenedCases.value.filter((item) => item.name.toLowerCase().includes(kw));
    });

    const selectCase = (caseType) => {
      console.log("选择案由:", caseType);
      // 这里可以添加选择案由的逻辑
    };

    const triggerFileUpload = () => {
      fileInput.value.click();
    };

    const handleFileSelect = (event) => {
      const file = event.target.files[0];
      if (file) {
        simulateUpload(file);
      }
    };

    const handleDragOver = () => {
      isDragOver.value = true;
    };

    const handleDragLeave = () => {
      isDragOver.value = false;
    };

    const handleDrop = (event) => {
      isDragOver.value = false;
      const files = event.dataTransfer.files;
      if (files.length > 0) {
        simulateUpload(files[0]);
      }
    };

    const simulateUpload = (file) => {
      uploadProgress.value = 0;
      const interval = setInterval(() => {
        uploadProgress.value += 10;
        if (uploadProgress.value >= 100) {
          clearInterval(interval);
          ocrResult.value = `已识别文件: ${file.name}\n答辩人：张三\n被答辩人：李四\n答辩意见：针对原告的诉讼请求，答辩人不予认可...`;
        }
      }, 200);
    };

    const downloadFile = () => {
      console.log("下载文件");
      // 这里添加下载逻辑
    };

    const shareFile = () => {
      console.log("分享文件");
      // 这里添加分享逻辑
    };

    // 处理上传选项
    const handleUploadOption = (option) => {
      showUploadOptions.value = false;
      console.log("选择上传方式:", option);
      
      // 模拟文件选择
      const mockFile = {
        name: `示例答辩状_${Date.now()}.pdf`,
        size: Math.floor(Math.random() * 5000000) + 100000, // 100KB - 5MB
        type: 'application/pdf',
        status: 'uploading',
        progress: 0
      };
      
      uploadList.value.push(mockFile);
      simulateFileUpload(mockFile);
    };

    // 模拟文件上传
    const simulateFileUpload = (file) => {
      const interval = setInterval(() => {
        file.progress += Math.floor(Math.random() * 20) + 5;
        if (file.progress >= 100) {
          file.progress = 100;
          file.status = 'success';
          clearInterval(interval);
        }
      }, 300);
    };

    // 删除文件
    const removeFile = (index) => {
      uploadList.value.splice(index, 1);
    };

    // 获取文件图标
    const getFileIcon = (type) => {
      if (type.includes('image')) return 'fas fa-image';
      if (type.includes('pdf')) return 'fas fa-file-pdf';
      if (type.includes('word') || type.includes('document')) return 'fas fa-file-word';
      return 'fas fa-file';
    };

    // 格式化文件大小
    const formatFileSize = (bytes) => {
      if (bytes === 0) return '0 B';
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    };

    return {
      currentStep,
      searchKeyword,
      uploadProgress,
      isDragOver,
      ocrResult,
      fileInput,
      showUploadOptions,
      uploadList,

      primaryCategories,
      selectedPrimary,
      caseMap,
      secondaryCases,
      filteredSecondaryCases,
      categoryList,
      expandedCategories,
      filteredSearchCases,

      selectCase,
      triggerFileUpload,
      handleFileSelect,
      handleDragOver,
      handleDragLeave,
      handleDrop,
      handleUploadOption,
      removeFile,
      getFileIcon,
      formatFileSize,
      downloadFile,
      shareFile,
    };
  },
};
</script>